import 'package:postx/src/tools/request.dart';
import 'dart:convert';

class res {
  String? alerMsg;
  Map<String, String>? headers;
  String? dataJson;
  res(this.alerMsg, this.headers, this.dataJson);
}

Future<res> sendsrv<T>(sendinfo) async {
  late res response;
  LineSplitter ls = const LineSplitter();
  List<String> infos = ls.convert(sendinfo);
  if (infos.isNotEmpty) {
    print("不为空: $infos");
    if ((infos[0].split(" ").length) > 1) {
      print("获取到原始信息: $infos");
      String rMethod = infos[0].split(" ")[0];
      String rUrl = infos[0].split(" ")[1];

      var responseT;
      switch (rMethod) {
        case "GET":
          responseT = await getRequestF(rUrl, infos);
          //返回判断是错误信息还是response结果
          if (responseT is String) {
            response = res("请求成功", null, responseT);
          } else {
            response = res(
                "请求成功", responseT.headers, jsonFormat(responseT.body.toString()));
          }
          break;
        case "POST":
          responseT = await postRequestF(rUrl, infos);
          print("收到了数据: $responseT");
          if (responseT is String) {
            response = res("请求成功", null, responseT);
          } else {
            response = res("请求成功", responseT.headers,
                jsonFormat(responseT.body.toString()));
          }
          break;
        default:
          response = res("参数错误", null, null);
          break;
      }
    } else {
      response = res("参数错误，URL有空格", null, null);
    }
  } else {
    response = res("参数错误", null, null);
  }
  return response;
}

///json字符串格式化
String jsonFormat(String jsonstr) {
  try {
    if (jsonstr.startsWith("{")) {
      //is jsonObject
      Map<String, dynamic> decode = const JsonCodec().decode(jsonstr);
      return _convert(decode, 0);
    } else if (jsonstr.startsWith("[")) {
      //is jsonArray
      List decode = json.decode(jsonstr);
      return _convert(decode, 0);
    } else {
      //错误的json格式
      print("Wrong format: $jsonstr");
      return "Wrong format: $jsonstr";
    }
  } catch (e) {
    print("${e.toString().trim()}\njson: $jsonstr");
    return "${e.toString().trim()}\njson: $jsonstr";
  }
}

///获取缩进空白符
String getDeepSpace(int deep) {
  var tab = StringBuffer();
  for (int i = 0; i < deep; i++) {
    tab.write("");
  }
  return tab.toString();
}

String _convert(dynamic object, int deep, {bool isObject = false}) {
  var buffer = StringBuffer();
  var nextDeep = deep + 1;

  if (object is Map) {
    var list = object.keys.toList();
    if (!isObject) {
      //如果map来自某个字段，则不需要显示缩进
      buffer.write("${getDeepSpace(deep)}");
    }
    buffer.write("{");
    if (list.isEmpty) {
      //当map为空，直接返回‘}’
      buffer.write("}");
    } else {
      buffer.write("\n");
      for (int i = 0; i < list.length; i++) {
        buffer.write("${getDeepSpace(nextDeep)}\"${list[i]}\":");
        buffer.write(_convert(object[list[i]], nextDeep, isObject: true));
        if (i < list.length - 1) {
          buffer.write(",");
          buffer.write("\n");
        }
      }
      buffer.write("\n");
      buffer.write("${getDeepSpace(deep)}}");
    }
  } else if (object is List) {
    if (!isObject) {
      //如果list来自某个字段，则不需要显示缩进
      buffer.write("${getDeepSpace(deep)}");
    }
    buffer.write("[");
    if (object.isEmpty) {
      //当list为空，直接返回‘]’
      buffer.write("]");
    } else {
      buffer.write("\n");
      for (int i = 0; i < object.length; i++) {
        buffer.write(_convert(object[i], nextDeep));
        if (i < object.length - 1) {
          buffer.write(",");
          buffer.write("\n");
        }
      }
      buffer.write("\n");
      buffer.write("${getDeepSpace(deep)}]");
    }
  } else if (object is String) {
    //为字符串时，需要添加双引号并返回当前内容
    buffer.write("\"$object\"");
  } else if (object is num || object is bool) {
    //为数字或者布尔值时，返回当前内容
    buffer.write(object);
  } else {
    //如果对象为空，则返回null字符串
    buffer.write("null");
  }
  return buffer.toString();
}
